package com.dfbz.demo01_卖票案例;

import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;

/**
 * @author lscl
 * @version 1.0
 * @intro:
 */
public class Demo14_Callable案例 {


    public static void main(String[] args) throws Exception{

//        sync();

        async();
    }


    public static void async()throws Exception {
        long startTime = System.currentTimeMillis();
        Api api = new Api();

        Callable<String> sendMsgTask = new Callable<String>() {
            @Override
            public String call() throws Exception {
                String res = api.sendMsg();
                return res;
            }
        };


        Callable<String> uploadTask = new Callable<String>() {
            @Override
            public String call() throws Exception {
                String res = api.upload();
                return res;
            }
        };


        FutureTask<String> t1 = new FutureTask<>(sendMsgTask);
        FutureTask<String> t2 = new FutureTask<>(uploadTask);

        new Thread(t1).start();
        new Thread(t2).start();


        String res_1 = t1.get();
        String res_2 = t1.get();

        System.out.println("res_1" + res_1);
        System.out.println("res_2" + res_2);

        long endTime = System.currentTimeMillis();
        System.out.println("同步花费的时间为: " + (endTime - startTime));

    }

    public static void sync() {

        long startTime = System.currentTimeMillis();

        Api api = new Api();
        String res_1 = api.sendMsg();
        String res_2 = api.upload();

        System.out.println("res_1" + res_1);
        System.out.println("res_2" + res_2);
        long endTime = System.currentTimeMillis();

        System.out.println("同步花费的时间为: " + (endTime - startTime));


    }
}

class Api {

    public String sendMsg() {

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("发送短信..");

        return "ok";
    }


    public String upload() {

        try {
            Thread.sleep(1500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("下载任务..");
        return "ok";
    }

}
